package com.lanhao.aot.carrierintegration.posteitaliane;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;

/**
  *   目前在用的
 * @author kunzhou3
 */
public class PosteItalianeUtil {
	private static final Logger LOG = LoggerFactory.getLogger(PosteItalianeUtil.class);

	public static final String URL_TEST = "https://sengiexpress.com/test-api/2";
	public static final String URL_PROD = "https://sengiexpress.com/api-v2/";
	
	public static final String URL = URL_PROD;
	
//	public static final String USER_NAME = "C10003";
//	public static final String USER_PWD = "dPZ2KRS6erQ=";
	public static final String USER_NAME = "C10023";
	public static final String USER_PWD = "MjAyMi0wOS0xNg==";
	
	// 正式参数
	// 账号：C10023
	// 密码：MjAyMi0wOS0xNg==
	// Token：QzEwMDIzJk1qQXlNaTB3T1MweE5nPT0=
	
	public static final String COUNTRY_CODE = "IT";
	public static final String CARRIER = "Posteitaliane";
	public static final Double DEFAULT_WEIGHT = 0.14d;
	public static final String DEFAULT_DEPOT = "CAN03";
	public static final String DEFAULT_CURRENCY = "EUR";
	public static final String DEFAULT_FILE_TYPE = "PDF";

	public static final String ORDER_URL = "/di-order/create";
	public static final String TRACKING_URL = "https://tt.sengiexpress.com/api-v2/tracking";

	public static void main(String[] args) {
//		System.out.println(getHeader());
		createOrder();
//		trackingOrder("5P52C20000346");
	}

	public static Map<String, String> getHeader() {
		HashMap<String, String> header = Maps.newHashMap();
		String value = Base64.encode(USER_NAME + "&" + USER_PWD);
		header.put("Authorization", "Basic " + value);
		return header;
	}

	public static void createOrder() {
		String orderUrl = URL + ORDER_URL;
		JSONObject request = new JSONObject();
		request.put("customerOrderNumber", UUID.fastUUID().toString(true).substring(16));
		request.put("prodCode", "CR");
		request.put("declareTypeCode", "4");
//		request.put("insuranceCoverage", "0");
//		request.put("insuranceCurrency", "RMB");
		request.put("iossNumber", "IM0123456789"); // TODO 填什么
//		request.put("codValue", 10.00);
//		request.put("codValueCurrency", "EUR");
//		request.put("dutyTerm", "DDU");
		request.put("shippingFee", 0.00);
//		request.put("shippingVat", 0.00);
		request.put("shippingFeeCurrency", DEFAULT_CURRENCY);
		request.put("depot", DEFAULT_DEPOT);
		JSONObject parcel = new JSONObject();
//		parcel.put("length", "0");
//		parcel.put("width", "0");
//		parcel.put("height", "0");
		parcel.put("weight", DEFAULT_WEIGHT);
		parcel.put("labelAccess", DEFAULT_FILE_TYPE);
//		parcel.put("markNo", "");
		
		JSONArray contentList = new JSONArray();
		JSONObject contentItem = new JSONObject();
		contentItem.put("eName", "AnHeGoods");
		contentItem.put("origName", "安和退货商品");
		contentItem.put("hsCode", "6000101111");
		contentItem.put("quantity", 1);
		contentItem.put("unitPrice", 0.00);
		contentItem.put("unitPriceCurrency", DEFAULT_CURRENCY);
		contentItem.put("unitWeight", DEFAULT_WEIGHT);
//		contentItem.put("productUrl", "");
//		contentItem.put("sku", "");
//		contentItem.put("vat", "");
		contentList.add(contentItem);
		parcel.put("contentList", contentList);
		
		JSONObject receiver = new JSONObject();
		receiver.put("countryCode", COUNTRY_CODE);
		receiver.put("firstName", "SG24 Warehouse");
//		receiver.put("lastName", "Bruni");
//		receiver.put("company", "");
		receiver.put("street", "Via Cairoli 59");
		receiver.put("city", "Roma");
//		receiver.put("email", "");
		receiver.put("province", "RM");
		receiver.put("zipCode", "00185");
//		receiver.put("phoneAreaCode", "0039");
		receiver.put("phone", "3778269469");
//		receiver.put("houseNumber", "");
//		receiver.put("receiverCode", null);
		parcel.put("receiver", receiver);
		
		
		JSONObject sender = new JSONObject();
		sender.put("countryCode", "CN");
		sender.put("firstName", "Aaron Wong");
//		sender.put("lastName", "Wong");
//		sender.put("company", "sengiexpress");
		sender.put("street", "Block A Floor 5, shixia road 8, baiyunhu street");
		sender.put("city", "Guangzhou");
		sender.put("province", "GuangDong");
		sender.put("zipCode", "510410");
//		sender.put("phone", "18576051313");
//		sender.put("phoneAreaCode", "86");
//		sender.put("houseNumber", "002");
//		sender.put("senderCode", null);
		parcel.put("sender", sender);
		request.put("parcel", parcel);

		Map<String, String> header = getHeader();
		LOG.info("开始请求意大利标签，请求url={}，header={}, 参数request={}", orderUrl, header, request.toJSONString());
		String respBody = HttpRequest.post(orderUrl).addHeaders(header).body(request.toJSONString()).execute().body();
		LOG.info("结束调用意大利标签，返回结果respBody={}", respBody);
		if (StringUtils.isNotBlank(respBody)) {
			JSONObject respObject = JSON.parseObject(respBody);
			Integer code = respObject.getInteger("code");
			String message = respObject.getString("message");
			if (code == 100) {
				JSONObject itemObject = respObject.getJSONObject("item");
				String labelUrl = itemObject.getString("labelUrl");
				String trackingNumber = itemObject.getString("trackingNumber");
				LOG.info("下单成功，获取标签信息labelUrl={},trackingNumber={}", labelUrl, trackingNumber);
			} else {
				LOG.info("下单失败了，message={}", message);
			}
		}

	}
	
	/**
	 * 轨迹跟踪
	 */
	public static void trackingOrder(String trackingNumber) {
		Map<String, String> header = getHeader();
		List<String> trackingNumberList = Lists.newArrayList(trackingNumber);
		JSONObject request = new JSONObject();
		request.put("trackingNumberList", trackingNumberList);
		LOG.info("开始请求意大利轨迹标签，请求url={}，header={}, 参数request={}", TRACKING_URL, header, request.toJSONString());
		String respBody = HttpRequest.post(TRACKING_URL).addHeaders(header).body(request.toJSONString()).execute().body();
		LOG.info("结束调用意大利轨迹标签，返回结果respBody={}", respBody);
		// {"5P52C20000346":[{"trackingNumber":"5P52C20000346","eventCode":"20","description":"Arrived at Sort Facility, CHINA","location":"DONGGUAN","eventTime":"2022-07-06T21:59:24"},{"trackingNumber":"5P52C20000346","eventCode":"30","description":"Departed from Sort Facility, CHINA","location":"CAN03","eventTime":"2022-07-07T08:46:31"},{"trackingNumber":"5P52C20000346","eventCode":"40","description":"Departed from Orignal Airport, CHINA","location":"HKG01","eventTime":"2022-07-08T19:44:00"},{"trackingNumber":"5P52C20000346","eventCode":"50","description":"Arrived at Destinated Airport, Customs clearance processing","location":"MXP01","eventTime":"2022-07-10T02:14:00"},{"trackingNumber":"5P52C20000346","eventCode":"60","description":"Customs clearance completed","location":"MXP01","eventTime":"2022-07-12T15:00:00"},{"trackingNumber":"5P52C20000346","eventCode":"70","description":"Shipment in transit to Posteitaliane","location":"MXP01","eventTime":"2022-07-12T18:00:00"},{"trackingNumber":"5P52C20000346","eventCode":"80","description":"Delivery to Posteitaliane","location":"82838","eventTime":"2022-07-12T19:00:00"}]}
	}
}
